<?php
/**
 * 复制表单重复提交验证器。
 * 维护表单提交的token队列
 * @author Ju <hipop@126.com>
 *
 */
class Application_Validate_Formtoken extends Zend_Validate_Abstract
{
	const NOT_MATCH = 'doNotResubmit';
	
	/**
	 * 表单token存放队列，session命名空间
	 * @var string
	 */
	const FORMTOKENLST = 'FORMTOKENLST';

    protected $_messageTemplates = array(
        self::NOT_MATCH => '请不要重复提交表单！'
    );
	
	
	private $_listLength = 10; 
	private $_tokenList; //固定长度数组
	private $_sessionTokenLst;
	
	public function __construct(){
		Zend_Session::start();
		$this->_sessionTokenLst = new Zend_Session_Namespace(self::FORMTOKENLST);
		$this->_getTokenList();
	}
	
	/**
	 * 从session中获取token队列
	 * Enter description here ...
	 */
	private function _getTokenList(){
		$this->_tokenList = $this->_sessionTokenLst->TOKENLIST;
		$this->_tokenList = is_array($this->_tokenList)?$this->_tokenList:array();
	}
	
	/**
	 * 将队列放入session
	 * Enter description here ...
	 * @param array $tokenlist
	 */
	private function _setTokenList($tokenlist=NULL){
		$tokenlist = is_array($tokenlist)?$tokenlist:array();
		if(count($tokenlist)>$this->_listLength){
			array_shift($tokenlist);
			return $this->_setTokenList($tokenlist);
		}
		$this->_sessionTokenLst->TOKENLIST = $tokenlist;
	}
	
	/**
	 * 忘掉某次token
	 * @param string $targetToken
	 * @return void
	 */
	public function forgetOnce($targetToken){
		echo $targetToken ,"\n";
		$targetKeys = array_keys($this->_tokenList,$targetToken);
		foreach ($targetKeys as $key){
			echo $key;
			unset($this->_tokenList[$key]);
		}
		print_r($this->_tokenList);
		$this->_setTokenList($this->_tokenList);
	}
	/**
	 * 检查token
	 * Enter description here ...
	 * @param string $token
	 * @return boolean
	 */
	public function check($token){
		$this->_getTokenList();
		//print_r($this->_tokenList);
		//die();
		if (in_array($token,$this->_tokenList)){
			$this->_error(self::NOT_MATCH);
			return FALSE;	
		}else {
			array_push($this->_tokenList ,$token);
			$this->_setTokenList($this->_tokenList);
			return TRUE;
		}
	}
	
	/* (non-PHPdoc)
	 * @see Zend_Validate_Interface::isValid()
	 */
	public function isValid($value) {
		// TODO Auto-generated method stub
		return $this->check($value);
	}

}